package com.gbiac.toc.api.eventapi.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gbiac.toc.api.eventapi.vo.*;
import com.gbiac.toc.event.entity.EventEntity;
import com.gbiac.toc.utils.CommonsUtils;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.JSONHelper;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gbiac.toc.api.eventapi.service.EventApiService;
import com.gbiac.toc.api.userapi.service.UserInfoService;
import com.gbiac.toc.api.userapi.vo.UserInfo;
import com.gbiac.toc.common.AjaxApiJson;
import com.gbiac.toc.common.service.AppLogService;
import com.gbiac.toc.common.service.UpdateDatabaseService;
import com.gbiac.toc.dynamics.entity.EventDynamicsEntity;
import com.gbiac.toc.messagePush.Jpush;

/**
 * 事件相关接口
 *
 * @author zys
 */
@Controller
@RequestMapping("/eventApi")
public class EventApiController {

  private static final Logger logger = Logger.getLogger(EventApiController.class);
  @Autowired
  private UpdateDatabaseService updateDatabaseService;
  @Autowired
  private EventApiService eventApiService;
  @Autowired
  private AppLogService appLogService;
  @Autowired
  private UserInfoService userInfoService;
  @Autowired
  private SystemService systemService;


  /**
   * 统计事件总数
   *
   * @param userId
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "getEventCount")
  @ResponseBody
  public AjaxApiJson getEventCount(String userId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      EventCountVo vo = eventApiService.getEventCount(userId);
      j.setSuccess(true);
      j.setMsg("查询成功");
      j.setData(vo);
    } catch (Exception e) {
      logger.error("查询事件总数接口出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("查询错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 获取事件列表
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "getEventList")
  @ResponseBody
  public AjaxApiJson getMyEventInfo(String body, HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> map = JSONHelper.json2Map(body);
    AjaxApiJson j = new AjaxApiJson();
    if (StringUtils.isBlank(body)) {
      j.setSuccess(false);
      j.setMsg("参数不能为空!");
    }
    try {
      String userId = map.get("userId").toString();// 用户ID
      String departId = map.get("departId").toString();//部门ID
      String eventType = map.get("eventType").toString();// 事件类型
      String eventStatus = map.get("eventStatus").toString();// 主事件状态
      String subStatus = map.get("subStatus").toString();// 子状态
      String page = map.get("page").toString();//页码--第几页
      String pageSize = map.get("pageSize").toString();//页数--一页显示多少条
      if (StringUtils.isBlank(userId)) {
        throw new Exception("用户ID不能为空");
      }
      EventVo vo = new EventVo();
      String msg = "";
      if (StringUtils.isNotBlank(eventType) && eventType.equals("1")) {// 我的事件
        vo = eventApiService.getMyEventInfo(userId, eventStatus, subStatus, page, pageSize);
        msg = "我的事件列表查询成功";
        try {//更新角标数据
          eventApiService.updateTocIndex(userId, eventType);
        } catch (Exception e) {
        }
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("2")) {// 待审核事件
        vo = eventApiService.getApplyingEventList(userId, departId, subStatus, page, pageSize);
        msg = "待审核事件列表查询成功";
        try {//更新角标数据
          eventApiService.updateTocIndex(userId, eventType);
        } catch (Exception e) {
        }
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("3")) {// 部门事件
        vo = eventApiService.getDepartEventList(userId, eventStatus, subStatus, page, pageSize);
        msg = "部门事件列表查询成功";
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("4")) {// 全部事件
        vo = eventApiService.getAllEventList(userId, eventStatus, subStatus, page, pageSize);
        msg = "全部事件列表查询成功";
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("5")) {// 重点关注事件
        vo = eventApiService.getFocusdEventList(userId, eventStatus, subStatus, page, pageSize);
        msg = "重点关注事件列表查询成功";
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("6")) {// 无责任部门事件
        vo = eventApiService.getUnDepartEventList(userId, eventStatus, subStatus, page, pageSize);
        msg = "无责任部门事件列表查询成功";
        try {//更新角标数据
          eventApiService.updateTocIndex(userId, eventType);
        } catch (Exception e) {
        }
      } /*
             * else if(StringUtils.isNotBlank(eventType) &&
             * eventType.equals("7")){//工程项目事件 vo =
             * eventApiService.getProjectEventList(userId, eventStatus,
             * subStatus); }
             */ else if (StringUtils.isNotBlank(eventType) && eventType.equals("8")) {// 我填报的事件--公服
        vo = eventApiService.getMyAddEventList(userId, eventStatus, subStatus, page, pageSize);
        msg = "我填报的事件列表查询成功";
      } else if (StringUtils.isNotBlank(eventType) && eventType.equals("9")) {// 我填报的事件--非公服
        vo = eventApiService.getMyAddEventListNot(userId, eventStatus, subStatus, page, pageSize);
        msg = "我填报的事件列表查询成功";
      }

      j.setSuccess(true);
      j.setMsg(msg);
      j.setData(vo);
    } catch (Exception e) {
      logger.error("获取事件列表内容出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("获取事件列表内容错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 获取事件详情
   */
  @RequestMapping(params = "getEventInfo")
  @ResponseBody
  public AjaxApiJson getEventInfo(String eventId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      EventInfoVo event = eventApiService.getEventInfo(eventId);
      j.setSuccess(true);
      j.setMsg("获取事件内容成功");
      j.setData(event);
    } catch (Exception e) {
      logger.error("获取事件内容出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("获取事件内容错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 事件的搜索
   */
  @RequestMapping(params = "searchEvent")
  @ResponseBody
  public AjaxApiJson searchEvent(String body, HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> map = JSONHelper.json2Map(body);
    AjaxApiJson j = new AjaxApiJson();
    try {
      Map<String, Object> resultMap = new HashMap<String, Object>();
      List<Event> event = eventApiService.searchEventByParam(map);
      if (event.isEmpty()) {
        j.setMsg("没有数据");
        return j;
      }
      long sum = eventApiService.getEventListSum(map);
      resultMap.put("total", sum);
      resultMap.put("eventList", event);
      j.setSuccess(true);
      j.setMsg("搜索事件成功");
      j.setData(resultMap);
    } catch (Exception e) {
      logger.error("搜索事件出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("搜索事件错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  // 事件类型查询
  @RequestMapping(params = "searchEventTypeName")
  @ResponseBody
  public AjaxApiJson searchEventTypeName(String typeId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      List<EventTypeVo> vo = eventApiService.findEventTypeList(typeId);
      j.setSuccess(true);
      j.setMsg("查询成功");
      j.setData(vo);
    } catch (Exception e) {
      logger.error("查询事件类型出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("查询事件类型错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  // 事件关注
  @RequestMapping(params = "focusEvent")
  @ResponseBody
  public AjaxApiJson focusEvent(@RequestBody Map map, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      eventApiService.focusEvent(map);
      j.setSuccess(true);
      j.setMsg("关注成功");
      j.setData("");
    } catch (Exception e) {
      logger.error("关注事件出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("关注事件错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 修改或者新增事件
   * @param event
   * @param pic 1: 整改前图片 2整改后图片
   * @param urls 图片ruls
   * @param beforStatus
   * @param info
   * @param userName
   * @param depName
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "saveOrUpdateEvent")
  @ResponseBody
  public AjaxApiJson addAppEvent(@RequestBody EventEntityVo event,
                                 @RequestParam(value = "pic", required = false) String pic,
                                 @RequestParam(value = "urls", required = false) String urls,
                                 @RequestParam(value = "beforStatus", required = false) String beforStatus,
                                 @RequestParam(value = "info", required = false) String info,
                                 @RequestParam(value = "userName", required = false) String userName,
                                 @RequestParam(value = "depName", required = false) String depName,
                                 HttpServletRequest request, HttpServletResponse response) {

    AjaxApiJson j = new AjaxApiJson();
    String message = "添加成功";
    // 判断请求的有效性，对每个请求添加保存一个tokenFilter
    // 格式：event.getId() + "," + event.getStatus() + "," + event.getContent() + request.getRequestURL()
    if (filterRequest(request,event.getId(),event.toString()+ "," + request.getHeader("Referer"))) {
      return j;
    }

    String id = event.getId();
    String createId = event.getUserid();
    // 获取提报人角色，若提报人是部门坐席或委外坐席，设置状态为待指派
    String roleCodes = userInfoService.getUserRoleCode(createId);
    if ("admanger".equals(roleCodes) && event.getStatus() == 1){
      // 如果是委外坐席或是部门坐席,状态变成待指派
      event.setStatus(2);
      event.setCheckStatus(6);//??
      // 责任部门清除
      event.setDepart(null);
    }

    // 设置事件为未接收
    event.setIsrecive(0);
    try {
      if (StringUtils.isBlank(id)) {//若事件还未保存到数据库，则设置初始化属性
        event.setIsdelete(0);//设置未删除
        event.setTimeoutStatus(1);//设置未超时
        event.setUserid(event.getUserid());
        event.setCreateDate(new Date());
        event.setNumber("");//设置事件编号
      }
      //调用业务层方法保存事件到数据库，并获取返回的事件id
      String neweventId = eventApiService.addAppEvent(event, id);
      // 1 整改前图片 2整改后图片
      // 回调数据库
      if (StringUtils.isNotBlank(urls)) {
        String[] url = urls.split(",");
        for (int k = 0; k < url.length; k++) {
          if ("1".equals(pic)) { // 整改前的图片
            if (StringUtils.isBlank(id)) {
              updateDatabaseService.updateUrlBefore(url[k], neweventId, k);
            } else {
              updateDatabaseService.updateUrlBefore(url[k], id, k);
            }
          } else if ("2".equals(pic)) {
            if (StringUtils.isBlank(id)) {
              updateDatabaseService.updateUrlAfter(url[k], neweventId, k);
            } else {
              updateDatabaseService.updateUrlAfter(url[k], id, k);
            }
          }
        }
      }
      Integer status = event.getStatus();
      String afterStatus = status + "";
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String eventCreateDate = sdf.format(event.getCreateDate());
      String receipt = event.getRecipient();
      if (StringUtils.isNotBlank(neweventId)) {
        this.aduitEvent(neweventId, userName, depName, beforStatus, afterStatus, eventCreateDate, info, receipt, event);
        JSONObject obj = new JSONObject();
        obj.put("eventId", neweventId);
        j.setSuccess(true);
        j.setMsg("新增事件成功");
        j.setData(obj);
      } else {
        this.aduitEvent(id, userName, depName, beforStatus, afterStatus, eventCreateDate, info, receipt, event);
        // 添加动态
        j.setSuccess(true);
        j.setMsg("修改事件成功");
        j.setData("");
      }

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("新增或者修改事件出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("新增或者修改事件出错：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 过滤请求
   *
   * @param request
   * @param key
   * @param value
   * @return
   */
  private boolean filterRequest(HttpServletRequest request, String key, String value) {
    try {

      RequestFilterEntity requestFilterEntity = (RequestFilterEntity) request.getSession().getAttribute(key);
      // 新的token值
      String newTokenFilter = CommonsUtils.EncoderByMd5(value);
      // 获取当前的时间
      long currentTime = System.currentTimeMillis();

      if (requestFilterEntity != null) {
        // 获取保存的token
        String tokenFilter = requestFilterEntity.getTokenFilter();
        // 获取上次请求的时间
        long lastRequsetTime = requestFilterEntity.getCurrentTime();

        // 每次请求的时间间隔为5s
        if ((currentTime - lastRequsetTime) < 5000) {
          if (StringUtils.isNotBlank(tokenFilter) && newTokenFilter.equals(tokenFilter)) {
            // 重复请求
            return true;
          }
        } else {
          return false;
        }
      }

      // 更新token
      request.getSession().setAttribute(key, new RequestFilterEntity(newTokenFilter, currentTime));

    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * 添加事件回复
   *
   * @param map
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "saveEventComment")
  @ResponseBody
  public AjaxApiJson addAppEventComment(@RequestBody Map map, HttpServletRequest request,
                                        HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      eventApiService.addAppEventComment(map);
      j.setSuccess(true);
      j.setMsg("新增事件评论成功");
      j.setData("");
      String userId = map.get("userId").toString();//用户id
      String createBy = map.get("userName").toString();//账号
      String createName = map.get("realName").toString();//真实名字
      String eventId = map.get("eventId").toString();//事件ID
      String comment = map.get("comment").toString();//评论内容
      //得到处理人
//          String receipt = eventInfo.getRecipient();//处理人
      String receipt = eventApiService.getTocEventById(eventId);

      //得到部门id
      String depid =eventApiService.getDepIdByUserId(userId);
      if(StringUtils.isNotBlank(receipt)){
        if(!userId.equals(receipt)) {
          // 评论推送
          String imei = eventApiService.getUserImei(receipt);
          List<String> list = new ArrayList<String>();
          list.add(imei);
          Map<String, String> extrasMap = new HashMap<>();
          extrasMap.put("12", eventId);// 事件ID
          Jpush jpush = new Jpush(list, createName + "刚刚回复了事件", comment, extrasMap, 1);
          try {
            jpush.sendPush();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      } else {
        if (StringUtils.isNotBlank(depid)) {
          List list = eventApiService.findFreeYourselfAduitUser(depid, userId);
          if (!list.isEmpty() && list.size() > 0 ) {
            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("12", eventId);// 事件ID
            Jpush jpush = new Jpush(list, createName + "刚刚回复了事件", comment, extrasMap, 1);
            try {
              jpush.sendPush();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      logger.error("新增事件评论出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("新增事件评论出错：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 添加事件动态
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "saveEventDymanics")
  @ResponseBody
  public AjaxApiJson addAppEventDymanics(@RequestBody Map map, HttpServletRequest request,
                                         HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      eventApiService.addAppEventDymanics(map);
      j.setSuccess(true);
      j.setMsg("新增事件动态成功");
      j.setData("");

      String userId = map.get("userId").toString();//用户id
      String eventId = map.get("eventId").toString();//事件ID
      String createName = map.get("userName").toString();//用户名
      String content = map.get("dycontent").toString();
      EventInfoVo eventInfo = eventApiService.getEventInfo(eventId);
//			&& "8a8a8b305f03bce1015f03e9fcbb0030".equals(eventInfo.getDepartId())//判断是否是公服
      String depid =eventApiService.getDepIdByUserId(userId);
      if (StringUtils.isNotBlank(depid)) {
        List list = eventApiService.findFreeYourselfAduitUser(depid,userId);
        Map<String, String> extrasMap = new HashMap<>();
        extrasMap.put("12", eventId);// 事件ID
        Jpush jpush = new Jpush(list, createName + "刚刚添加了新动态", content, extrasMap, 1);
        try {
          jpush.sendPush();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("新增事件动态出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("新增事件动态出错：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 事件审核添加动态
   */
  //之前状态没有 事件ID   info空  createdate 空
  public String aduitEvent(String eventId, String userName, String depName, String beforStatus, String afterStatus,
                           String eventCreateDate, String info, String receipt, EventEntityVo eventVo) {
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("eventId", eventId);
      map.put("userName", userName);
      map.put("depName", depName);
      map.put("beforStatus", beforStatus);
      map.put("afterStatus", afterStatus);
      map.put("eventCreateDate", eventCreateDate);
      map.put("info", info);
      EventDynamicsEntity entity = new EventDynamicsEntity();
      String time = DateUtils.getDate("MM-dd HH:mm");
      String content = "";
      if (eventVo.getContent().length() <= 10) {
        content = eventVo.getContent();
      } else {
        content = eventVo.getContent().substring(0, 10);
      }

      // 计算处理时间
      int dealTime = 0;
      if (StringUtils.isNotBlank(eventCreateDate)) {
        dealTime = DateUtils.dateDiff('m', DateUtils.getCalendar(),
                DateUtils.parseCalendar(eventCreateDate, "yyyy-MM-dd HH:mm:ss"));
      }
      if (!beforStatus.equals(afterStatus)) {
        if (beforStatus.equals("3") && afterStatus.equals("2")) {// 不同意，事件退回
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "退回事件;原因：" + info);
        } else if (beforStatus.equals("1") && afterStatus.equals("2")) {// 审核通过进入待指派
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "审核通过");

          //事件推送
          String imei = eventApiService.getUserImei(eventVo.getUserid());
          List<String> list = new ArrayList<String>();
          if (StringUtils.isNotBlank(imei)) {
            list.add(imei);
          }

          Map<String, String> extrasMap = new HashMap<>();
          extrasMap.put("9", eventId);// 事件ID
          if (!list.isEmpty()) {
            Jpush jpush = new Jpush(list, userName + "审核通过了您填报的事件", content, extrasMap, 1);
            try {
              jpush.sendPush();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }

          try {
            //获取角标
            TocIndex index = eventApiService.getTocIndex(eventVo.getUserid());
            //if(StringUtils.isNotBlank(index.getId())){
            int fillTotal = index.getFillTotal() + 1;
            eventApiService.modifyTocIndex(eventVo.getUserid(), "6", fillTotal);//跳转到我的页面
            //}
          } catch (Exception e) {

          }


        } else if (beforStatus.equals("3") && afterStatus.equals("8")) {// 下派,处理中（4）修改为下派，未接收（8）
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          UserInfo userInfo = userInfoService.getUserInformation(receipt);
          entity.setDycontent(time + userName + "下派事件给" + userInfo.getRealName() + "进行处理");
          try {
            eventApiService.updateIsrecive(eventId);
          } catch (Exception e) {

          }

          if (StringUtils.isNotBlank(receipt)) {
            // 事件推送
            String imei = eventApiService.getUserImei(receipt);
            List<String> list = new ArrayList<String>();
            if (StringUtils.isNotBlank(imei)) {
              list.add(imei);
            }
            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("2", eventId);// 事件ID
            if (!list.isEmpty()) {
              Jpush jpush = new Jpush(list, userName + "刚刚给您派发了新事件，请您及时处理", content, extrasMap, 1);
              try {
                jpush.sendPush();
              } catch (Exception e) {
                e.printStackTrace();
              }

            }
            try {
              //获取角标
              TocIndex index = eventApiService.getTocIndex(receipt);
              //if(StringUtils.isNotBlank(index.getId())){
              int myTotal = index.getMyTotal() + 1;
              eventApiService.modifyTocIndex(receipt, "1", myTotal);//跳转到我的页面
              //}
            } catch (Exception e) {

            }
          }
        } else if (beforStatus.equals("4") && afterStatus.equals("5")) {// 进入公服审核
          if (StringUtils.isNotBlank(info)) {
            entity.setCreateName(userName);
            entity.setCreateDate(new Date());
            entity.setEventId(eventId);
            entity.setDycontent(time + userName + "完成事件:" + info);
            eventApiService.updateEventDealTime(eventId, String.valueOf(dealTime));

            //查询审核人员公国验收，事件完成人应该验收
            List list = eventApiService.findEventUser(eventId);
            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("11", eventId);// 事件ID
            if (!list.isEmpty()) {
              Jpush jpush = new Jpush(list, userName + "刚刚完成了事件，请您及时验收", content, extrasMap, 1);
              try {
                jpush.sendPush();
              } catch (Exception e) {
                e.printStackTrace();
              }

            }

            try {
              List listId = eventApiService.getAduitUserId();
              if (listId != null && listId.size() > 0) {
                String userId = listId.get(0).toString();
                //获取角标
                TocIndex index = eventApiService.getTocIndex(userId);
                //if(StringUtils.isNotBlank(index.getId())){
                int aduitTotal = index.getAduitTotal() + 1;
                eventApiService.modifyTocIndex(userId, "2", aduitTotal);//跳转到我的页面
                //}
              }

            } catch (Exception e) {

            }

          } else {
            entity.setCreateName(userName);
            entity.setCreateDate(new Date());
            entity.setEventId(eventId);
            entity.setDycontent(time + userName + "完成事件");
            eventApiService.updateEventDealTime(eventId, String.valueOf(dealTime));

            // 事件推送
            List list = eventApiService.findAduitUser(eventVo.getDepart());
            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("11", eventId);// 事件ID
            if (!list.isEmpty()) {
              Jpush jpush = new Jpush(list, userName + "刚刚完成了事件，请您及时验收", content, extrasMap, 1);
              try {
                jpush.sendPush();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }

            try {
              List listId = eventApiService.getAduitUserId();
              if (listId != null && listId.size() > 0) {
                for (int i = 0; i < listId.size(); i++) {
                  String userId = listId.get(i).toString();
                  //获取角标
                  TocIndex index = eventApiService.getTocIndex(userId);
                  //if(StringUtils.isNotBlank(index.getId())){
                  int aduitTotal = index.getAduitTotal() + 1;
                  eventApiService.modifyTocIndex(userId, "2", aduitTotal);//跳转到我的页面
                  //}
                }

              }

            } catch (Exception e) {
              e.printStackTrace();
            }


          }
        } else if (beforStatus.equals("5") && afterStatus.equals("4")) {// 公服审核不通过退回
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "拒绝验收事件,原因：" + info);

          if (StringUtils.isNotBlank(receipt)) {
            // 事件推送
            String imei = eventApiService.getUserImei(receipt);
            List<String> list = new ArrayList<String>();
            if (StringUtils.isNotBlank(imei)) {
              list.add(imei);
            }

            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("10", eventId);// 事件ID
            if (!list.isEmpty()) {
              Jpush jpush = new Jpush(list, userName + "刚刚拒绝验收您完成的事件", content, extrasMap, 1);
              try {
                jpush.sendPush();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }

            try {
              //获取角标
              TocIndex index = eventApiService.getTocIndex(receipt);
              //if(StringUtils.isNotBlank(index.getId())){
              int myTotal = index.getMyTotal() + 1;
              eventApiService.modifyTocIndex(receipt, "1", myTotal);//跳转到我的页面
              //}
            } catch (Exception e) {

            }

          }
        } else if (beforStatus.equals("4") && afterStatus.equals("6")) {// TOC审核
          if (StringUtils.isNotBlank(info)) {
            entity.setCreateName(userName);
            entity.setCreateDate(new Date());
            entity.setEventId(eventId);
            entity.setDycontent(time + userName + "完成事件:" + info);
            eventApiService.updateEventDealTime(eventId, String.valueOf(dealTime));

          } else {
            entity.setCreateName(userName);
            entity.setCreateDate(new Date());
            entity.setEventId(eventId);
            entity.setDycontent(time + userName + "完成事件");
            eventApiService.updateEventDealTime(eventId, String.valueOf(dealTime));

          }
        } else if (beforStatus.equals("5") && afterStatus.equals("6")) {// 公服审核通过，进入TOC审核
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "验收通过事件");
          if (StringUtils.isNotBlank(receipt)) {
            // 事件推送
            String imei = eventApiService.getUserImei(receipt);
            List<String> list = new ArrayList<String>();
            if (StringUtils.isNotBlank(imei)) {
              list.add(imei);
            }

            Map<String, String> extrasMap = new HashMap<>();
            extrasMap.put("10", eventId);// 事件ID
            if (!list.isEmpty()) {
              Jpush jpush = new Jpush(list, userName + "刚刚验收通过了您完成的事件", content, extrasMap, 1);
              try {
                jpush.sendPush();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }

          }

        } else if (afterStatus.equals("7")) {// 事件关闭
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "关闭事件");

          // id获取事件
          try {
            EventEntity eventEntity = systemService.getEntity(EventEntity.class,eventId);
            // 设置关闭时间
            eventEntity.setCloseTime(new Timestamp(System.currentTimeMillis()));
          } catch (Exception e) {
            e.printStackTrace();
          }

          // 事件推送
          String imei = eventApiService.getUserImei(eventVo.getUserid());
          List<String> list = new ArrayList<String>();
          if (StringUtils.isNotBlank(imei)) {
            list.add(imei);
          }

          Map<String, String> extrasMap = new HashMap<>();
          extrasMap.put("8", eventId);// 事件ID,返回到我填报的事件
          if (!list.isEmpty()) {
            Jpush jpush = new Jpush(list, userName + "关闭了您填报的事件", content, extrasMap, 1);
            try {
              jpush.sendPush();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }


        } else if (beforStatus.equals("0") && afterStatus.equals("1")) {// 公服提交
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "上报事件");
          // 事件推送
          String depid =eventApiService.getDepIdByUserId(eventVo.getUserid());
          List list = eventApiService.findAduitUser(depid);
          Map<String, String> extrasMap = new HashMap<>();
          extrasMap.put("3", eventId);// 事件ID
          if (!list.isEmpty()) {
            Jpush jpush = new Jpush(list, userName + "刚刚填报了新事件，请您及时审核", content, extrasMap, 1);
            try {
              jpush.sendPush();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
          try {
            List listId = eventApiService.getAduitUserId();
            if (listId != null && listId.size() > 0) {
              for (int i = 0; i < listId.size(); i++) {
                String userId = listId.get(i).toString();
                //获取角标
                TocIndex index = eventApiService.getTocIndex(userId);
                //if(StringUtils.isNotBlank(index.getId())){
                int aduitTotal = index.getAduitTotal() + 1;
                eventApiService.modifyTocIndex(userId, "2", aduitTotal);//跳转到我的页面
                //}
              }

            }

          } catch (Exception e) {

          }

        } else if (beforStatus.equals("0") && afterStatus.equals("2")) {// 其他部门
          entity.setCreateName(userName);
          entity.setCreateDate(new Date());
          entity.setEventId(eventId);
          entity.setDycontent(time + userName + "上报事件");
        }
      }
      eventApiService.aduitEvent(map, entity);
    } catch (Exception e) {

    }
    return "1";
  }

  // 事件区域查询
  @RequestMapping(params = "searchEventArea")
  @ResponseBody
  public AjaxApiJson searchEventArea(String areaId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      List<EventAreaVo> vo = eventApiService.findEventAreaList(areaId);
      j.setSuccess(true);
      j.setMsg("查询区域成功");
      j.setData(vo);
    } catch (Exception e) {
      logger.error("查询事件区域出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("查询事件区域错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 查找派发人
   *
   * @param depId    部门ID
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "findEmployee")
  @ResponseBody
  public AjaxApiJson findEmployeeByDepid(String depId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      List<DepEmployeeVo> vo = eventApiService.findEmployeeByDepid(depId);
      j.setSuccess(true);
      j.setMsg("查询派发人成功");
      j.setData(vo);
    } catch (Exception e) {
      logger.error("查询派发人出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("查询派发人错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 获取角标数据
   *
   * @param userId
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "getTocIndex")
  @ResponseBody
  public AjaxApiJson getTocIndex(String userId, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      TocIndex vo = eventApiService.getTocIndex(userId);
      j.setSuccess(true);
      j.setMsg("查询成功");
      j.setData(vo);
    } catch (Exception e) {
      logger.error("查询角标接口出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("查询错误：" + e.getMessage());
      j.setData("");
    }
    return j;
  }


  /**
   * 填写预计完成时间
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "insertBudgetTime")
  @ResponseBody
  public AjaxApiJson insertBudegetTime(@RequestBody Map map, HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      //添加动态
      String userName = map.get("userName").toString();
      String depName = map.get("depName").toString();
      String eventId = map.get("eventId").toString();
      //String time = DateUtils.formatTime(new Date());
      String time = DateUtils.getDate("MM-dd HH:mm");

      // 判断请求的有效性，对每个请求添加保存一个tokenFilter
      if (filterRequest(request, eventId,eventId + "," + userName + "," + time + "," + request.getRequestURL().toString())) {
        return j;
      }

      eventApiService.insertBudgetTime(map);
      j.setSuccess(true);
      j.setMsg("填写预计完成时间成功");
      j.setData("");

      EventDynamicsEntity entity = new EventDynamicsEntity();
      entity.setCreateName(userName);
      entity.setCreateDate(new Date());
      entity.setEventId(eventId);
      entity.setDycontent(time + userName + "接收事件");
      eventApiService.aduitEvent(map, entity);//添加动态

    } catch (Exception e) {
      logger.error("填写预计完成时间成功标接口出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("填写预计完成时间失败：" + e.getMessage());
      j.setData("");
    }
    return j;
  }

  /**
   * 更新数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "updateData")
  @ResponseBody
  public AjaxApiJson updateData(HttpServletRequest request, HttpServletResponse response) {
    AjaxApiJson j = new AjaxApiJson();
    try {
      eventApiService.updateData();
    } catch (Exception e) {
      logger.error("更新数据出错：" + e.getMessage());
      j.setSuccess(false);
      j.setMsg("更新数据出错：" + e.getMessage());
      j.setData("");
    }
    return j;
  }
}
